package com.jpro.module.system.dal.mysql.logger;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.jpro.framework.common.pojo.PageResult;
import com.jpro.framework.mybatis.core.mapper.BaseMapperX;
import com.jpro.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.jpro.module.system.api.logger.dto.OperateLogPageReqDTO;
import com.jpro.module.system.controller.admin.logger.vo.operatelog.OperateLogPageReqVO;
import com.jpro.module.system.dal.dataobject.logger.OperateLogDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Mapper
public interface OperateLogMapper extends BaseMapperX<OperateLogDO> {

    default PageResult<OperateLogDO> selectPage(OperateLogPageReqVO pageReqDTO) {
        return selectPage(pageReqDTO, new LambdaQueryWrapperX<OperateLogDO>()
                .eqIfPresent(OperateLogDO::getUserId, pageReqDTO.getUserId())
                .eqIfPresent(OperateLogDO::getBizId, pageReqDTO.getBizId())
                .likeIfPresent(OperateLogDO::getType, pageReqDTO.getType())
                .likeIfPresent(OperateLogDO::getSubType, pageReqDTO.getSubType())
                .likeIfPresent(OperateLogDO::getAction, pageReqDTO.getAction())
                .betweenIfPresent(OperateLogDO::getCreateTime, pageReqDTO.getCreateTime())
                .orderByDesc(OperateLogDO::getId));
    }

    default PageResult<OperateLogDO> selectPage(OperateLogPageReqDTO pageReqDTO) {
        return selectPage(pageReqDTO, new LambdaQueryWrapperX<OperateLogDO>()
                .eqIfPresent(OperateLogDO::getType, pageReqDTO.getType())
                .eqIfPresent(OperateLogDO::getBizId, pageReqDTO.getBizId())
                .eqIfPresent(OperateLogDO::getUserId, pageReqDTO.getUserId())
                .orderByDesc(OperateLogDO::getId));
    }

    default int deleteDaysBefore(Integer days) {
        // 获取当前的LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        // 获取n天前的LocalDateTime
        LocalDateTime daysBeforeTime = LocalDateTimeUtil.offset(now, -days, ChronoUnit.DAYS);
        final LambdaQueryWrapper<OperateLogDO> queryWrapper = new LambdaQueryWrapper<OperateLogDO>().lt(OperateLogDO::getCreateTime, daysBeforeTime);
        return delete(queryWrapper);
    }

}
